﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.Xml.Linq;
using System.Runtime.InteropServices.Automation;

namespace SearchTweets
{
    public partial class MainPage : UserControl
    {
        ObservableCollection<SearchedTweets> objSearchedTweets = new ObservableCollection<SearchedTweets>();
        public MainPage()
        {
            InitializeComponent();
            Loaded += new RoutedEventHandler(MainPage_Loaded);
        }     

        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            lstTweets.ItemsSource = objSearchedTweets;
           // btnExport.IsEnabled = AutomationFactory.IsAvailable;
        }

        private void btnGetTweets_Click(object sender, System.Windows.RoutedEventArgs e)
        {
        	// TODO: Add event handler implementation here.
            if (!string.IsNullOrEmpty(txtSearchText.Text))
            {
                objSearchedTweets.Clear();
              //  lstTweets.ItemsSource = null;
                WebClient objWebClient = new WebClient();
                objWebClient.DownloadStringCompleted += (s, ra) =>
                {
                    XDocument doc = XDocument.Parse(ra.Result);
                    XNamespace ns = "http://www.w3.org/2005/Atom";
                    var items = from item in doc.Descendants(ns + "entry")
                                select new SearchedTweets()
                                {
                                    Title = item.Element(ns + "title").Value,
                                    Image = new Uri((from XElement xe in item.Descendants(ns + "link")
                                                     where xe.Attribute("type").Value == "image/png"
                                                     select xe.Attribute("href").Value).First<string>()),
                                    Link = new Uri((from XElement xe in item.Descendants(ns + "link")
                                                    where xe.Attribute("type").Value == "text/html"
                                                    select xe.Attribute("href").Value).First<string>())
                                };
                    foreach (SearchedTweets t in items)
                    {
                        objSearchedTweets.Add(t);
                    }                   
                };
                objWebClient.DownloadStringAsync(new Uri("http://search.twitter.com/search.atom?q=" + txtSearchText.Text));
            }
            else
            {
                MessageBox.Show("Type search text");
            }
        }

    }
}
